package com.example.dingdong.service;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.dingdong.daomain.RouterEntity;
import com.example.dingdong.repository.RouterRepository;

/**
 * @ClassName: RouterService
 * @Description: 路由服务层
 * @Author chengwenixng
 * @DateTime 2021-03-31 20:29:02
 */
@Service
public class RouterService {

	@Autowired
	private RouterRepository routerRepository;



	/**
	 * 保存路由实体
	 */
	@Transactional(rollbackFor = Exception.class)
	public RouterEntity saveRouter(RouterEntity router) {
		return routerRepository.save(router);
	}

	/**
	 * 查找路由实体
	 */
	public RouterEntity getRouter(int id, boolean delFlag) {
		return routerRepository.findByIdAndDelFlag(id, delFlag);
	}

	/**
	 * 查找所有路由
	 */
	public List<RouterEntity> getRouterList() {
		return routerRepository.findByDelFlag(true);
	}

	/**
	 * 查找路由集合
	 */
	public List<RouterEntity> getRouters(List<Integer> routerList, boolean delFlag) {
		return routerRepository.findByIdInDelFlag(routerList, delFlag);
	}

	/**
	 * 查找所有父级路由
	 */
	public List<RouterEntity> getParentRouter() {
		return routerRepository.findParentRouter();
	}

	/**
	 * 绑定路由实体
	 */
	@Transactional(rollbackFor = Exception.class)
	public void routerBind(RouterEntity parentRouter, RouterEntity childrenRouter) {
		parentRouter.getChildren().add(childrenRouter);
		childrenRouter.setParent(parentRouter);

		saveRouter(childrenRouter);
		saveRouter(parentRouter);
	}

	/**
	 * 删除路由实体
	 */
	@Transactional(rollbackFor = Exception.class)
	public void delRouter(RouterEntity router) {
		router.setDelFlag(false);
		saveRouter(router);
	}

	/**
	 * 更新路由实体
	 */
	@Transactional(rollbackFor = Exception.class)
	public void updateRouter(int id, String path, String component, String name, String icon, boolean strict,
			boolean exact, String redirect) {
		routerRepository.updateRouter(id, path, component, name, icon, strict, exact, redirect);
	}

	/**
	 * 更新并换绑路由实体
	 */
	@Transactional(rollbackFor = Exception.class)
	public void updateAndChangeBindRouter(int parentId, RouterEntity router, String path, int sort, String component,
			String name, String icon, boolean strict, boolean exact, String redirect) {
		// 1、获取父节点路由
		RouterEntity parentRouter = (parentId == -1) ? router.getParent() : getRouter(parentId, true);

		// 2、解绑父级路由
		if (parentRouter != null) {
			parentRouter.getChildren().remove(router);
			saveRouter(parentRouter);
		}

		// 3、更改子级路由实体并换绑
		routerRepository.updateAndChangeBindRouter(parentId, router.getId(), path, sort, component, name, icon, strict, exact,
				redirect);
	}

}
